﻿using System;
using System.Linq;
using Notoric.Commanding;
using Notoric.Gui.Windows;

namespace Notoric.Gui.Commands
{
    /// <summary>
    /// Implements a command for removing selected core symbols.
    /// </summary>
    public class RemoveCoreSymbolsCommand : MusicSelectionRibbonCommand
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="RemoveCoreSymbolsCommand"/> class.
        /// </summary>
        /// <param name="mainWindow">
        /// <para>
        /// Type: <see cref="MainWindow"/>
        /// </para>
        /// <para>
        /// The main application window.
        /// </para>
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="mainWindow"/> is <see langword="null"/>.
        /// </exception>
        public RemoveCoreSymbolsCommand(MainWindow mainWindow)
            : base(mainWindow)
        {
        }

        #endregion

        #region MusicSectionRibbonCommand Members

        /// <inheritdoc/>
        protected override bool CanExecuteCore(object parameter)
        {
            return Selection != null && Selection.Count(s => !(s is ViewModel.Elements.CWNotation.KeySignature || s is ViewModel.Elements.CWNotation.TimeSignature)) > 0;
        }

        #endregion

        #region ICommand Members

        /// <inheritdoc/>
        public override void Execute(object parameter)
        {
            var macro = new UndoableMacroCommand(ApplicationWindow.StackManager.ActiveUndoStack, ApplicationWindow.StackManager.ActiveRedoStack)
            {
                Name = "Remove Symbols"
            };

            foreach (var symbol in Selection)
            {
                if (symbol is ViewModel.Elements.CWNotation.Clef && symbol == symbol.FindOwner<ViewModel.Elements.CWNotation.Staff>().Symbols[0])
                    continue;
                else if (symbol is ViewModel.Elements.CWNotation.KeySignature || symbol is ViewModel.Elements.CWNotation.TimeSignature)
                    continue;

                var cmd = new ViewModel.RemoveCoreSymbolCommand(macro.UndoStack, macro.RedoStack)
                {
                    Symbol = symbol
                };
                macro.Commands.Add(cmd);
            }

            if (macro.Commands.Count > 0)
                macro.Execute(null);
        }

        #endregion
    }
}
